package com.attendance.aspectj;

import com.attendance.annotation.UserSession;
import com.attendance.spring.SpringAopUtils;
import com.attendance.spring.SpringMvcUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;

/**
 * 用户会话
 *
 * @author 今朝
 * @date 2021/03/15
 */
@Aspect
@Component
public class UserSessionAspect {

    @Pointcut("@annotation(com.attendance.annotation.UserSession)")
    public void annotationPointCut() {
    }

    @Before("annotationPointCut()")
    public void doBeforeReturning(JoinPoint joinPoint) {
        UserSession annotation = SpringAopUtils.getAnnotation(joinPoint, UserSession.class);
        if (annotation != null) {
            Object[] args = joinPoint.getArgs();
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Annotation[][] parameterAnnotations = signature.getMethod().getParameterAnnotations();
            for (int index = 0; index < parameterAnnotations.length; index++) {
                Annotation[] parameterAnnotation = parameterAnnotations[index];
                for (Annotation a : parameterAnnotation) {
                    if (a instanceof UserSession) {
                        Object arg = args[index];
                        System.out.println(SpringMvcUtils.getSession().getAttribute("USER"));
                        args[index] = SpringMvcUtils.getSession().getAttribute("USER");
                    }
                }
            }
        }
    }
}
